<?php

class Database
{
    private $db;

    public function __construct()
    {
        require_once '../config/database.php'; // 引入数据库配置文件
        $dsn = "{$config['driver']}:host={$config['host']};port={$config['port']};dbname={$config['database']};charset={$config['charset']}";
        
        try {
            $this->db = new PDO($dsn, $config['username'], $config['password'], $config['options']);
        } catch (PDOException $e) {
            error_log('Database connection failed: ' . $e->getMessage());
            die("Connection failed: " . $e->getMessage()); // 生产环境中，可以根据需要自定义错误提示
        }
    }

    // 执行查询
    public function query($sql, $params = [])
    {
        try {
            $stmt = $this->db->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log('Query failed: ' . $e->getMessage());
            return false;
        }
    }

    // 执行插入、更新或删除
    public function execute($sql, $params = [])
    {
        try {
            $stmt = $this->db->prepare($sql);
            return $stmt->execute($params);
        } catch (PDOException $e) {
            error_log('Execute failed: ' . $e->getMessage());
            return false;
        }
    }
}
